// +----------------------------------------------------------------------
// | CodeEngine
// +----------------------------------------------------------------------
// | Copyright 艾邦
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: TaoGe <liangtao.gz@foxmail.com>
// +----------------------------------------------------------------------
// | Version: 2.0 2019/7/11 15:22
// +----------------------------------------------------------------------
'use strict';

import Tool from './tool';

/**
 * 持久化存储类
 */
export default class Storage {

	constructor( instance ) {
		if ( Tool.empty( instance ) ) {
			throw new SyntaxError( 'Storage实例化instance不能为空' )
		}
		this.cache = instance;
	}

	static getInstance( instance ) {
		if ( !this.instance ) {
			this.instance = new Storage( instance );
		}
		return this.instance;
	}

	get( key ) {
		const encryptionKey = Tool.key( key );
		const value = this.cache.get( encryptionKey );
		if ( value === null || value === undefined ) {
			return undefined;
		}
		let data = Tool.decode( value );
		if ( Tool.empty( data ) ) {
			return undefined;
		}
		data = JSON.parse( data );
		if ( data.expiration === 0 ) {
			return data.data;
		}
		const expiration = new Date().getTime() - data.time;
		if ( expiration >= ( data.expiration * 1000 ) ) {
			this.cache.del( encryptionKey );
			return undefined;
		} else {
			return data.data;
		}
	}

	set( key, value, expiration = 0 ) {
		const encryptionKey = Tool.key( key );
		const string = JSON.stringify( {
			data: value,
			time: new Date().getTime(),
			expiration: expiration
		} );
		this.cache.set( encryptionKey, Tool.encode( string ) );
	}

	del( key ) {
		const encryptionKey = Tool.key( key );
		this.cache.del( encryptionKey )
	}

	clear() {
		this.cache.clear();
	}
}
